package middlewares

import (
	"gomicrov4-sharemod/gateway-api/utils"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

/*
 +----------------------------------------------------------------------
 + Title        : ZapLoggerMiddleware
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2021-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : zap logger中间件
 +----------------------------------------------------------------------
*/

/**
 * zap 日志中间件
 *
 * @author huwl
 * @date 2025/08/01 10:26:43
 */
func ZapLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		params, _ := utils.GetRequestParams(c)

		// 在中间件中添加错误记录
		if len(c.Errors) > 0 {
			utils.Zap.Error("请求错误",
				zap.String("path", path),
				zap.Any("errors", c.Errors.Errors()),
			)
		}

		c.Next() // 处理请求

		end := time.Now()
		latency := end.Sub(start)

		utils.Zap.Info("调用接口",
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.Any("params", params),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.Duration("latency", latency),
		)
	}
}
